const scaleController = {
	/**
	 * @Author: lcq
	 * @Date: 2024-04-25 09:18:12
	 * @description: 使节点可放大
	 * @param {Object} params - 配置参数对象
	 * @param {String} params.element - DOM节点
	 * @param {Float} params.minScale - 最小缩放值
	 * @param {Float} params.maxScale - 最大缩放值
	 * @param {Boolean} [params.button=true] - 是否显示还原按钮
	 * @param {Number} [params.rotate=0] - 还原按钮旋转角度
	 * @param {Boolean} [params.rebound=false] - 是否在缩放小于1时自动反弹回原大小
	 * @param {Number} [params.transition=600] - 缩放动画过渡时间（毫秒）
	 * @return {void}
	 */
	enablePinchZoom(params = {}) {
		let { element, minScale = 0.5, maxScale = 3, button = true, rotate = 0, rebound = true, transition = 600 } = params;
		button = !rebound;
		if (!!element.getAttribute('pinch-zoom')) throw new Error('该节点已添加过缩放功能');
		const pinchZoomId = scaleController.generateUniqueId();
		element.setAttribute('pinch-zoom', pinchZoomId);
		let scale = 1;
		let startScale = 1;
		let lastDistance = 0;
		let isScaling = false;
		let lastClientX = 0;
		let lastClientY = 0;
		let translateX = 0;
		let translateY = 0;
		let initialTransformOrigin = '';
		let reduction = undefined;
		if (button) {
			reduction = document.createElement('div');
			reduction.id = 'pinchZoomReduction' + pinchZoomId;
			reduction.style = `position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%) rotate(${rotate}deg); visibility: hidden; opacity: 0; transition: ${transition}ms; background: transparent; z-index: 99999999999999;`;
			let reductionBtn = document.createElement('button');
			reductionBtn.style =
				'font-size: 16px; padding: 5px 16px; border: none; border-radius: 5px; outline: none; background: rgba(0,0,0, 0.3); color: rgb(255 255 255);';
			reductionBtn.innerHTML = `还原`;
			reductionBtn.onclick = () => setToOriginal();
			reduction.appendChild(reductionBtn);
			element.parentNode.appendChild(reduction);
		}
		// 显示还原按钮
		function showButton() {
			if (!button) return;
			reduction.style.visibility = 'visible';
			reduction.style.opacity = 1;
		}
		// 隐藏还原按钮
		function hideButton() {
			if (!button) return;
			reduction.style.visibility = 'hidden';
			reduction.style.opacity = 0;
		}
		function handleTouchStart(event) {
			if (event.touches.length !== 2) return;
			isScaling = true;
			element.style.transition = '10ms linear';
			const touch1 = event.touches[0];
			const touch2 = event.touches[1];
			lastDistance = getDistance(touch1, touch2);
			startScale = scale;
			lastClientX = (touch1.clientX + touch2.clientX) / 2;
			lastClientY = (touch1.clientY + touch2.clientY) / 2;
			if (rebound) {
				// 记录初始的transformOrigin
				initialTransformOrigin = `${lastClientX}px ${lastClientY}px`;
				element.style.transformOrigin = initialTransformOrigin;
			}
		}
		function handleTouchMove(event) {
			if (!isScaling && event.touches.length !== 2) return;
			event.preventDefault();
			const touch1 = event.touches[0];
			const touch2 = event.touches[1];
			const currentDistance = getDistance(touch1, touch2);
			const currentClientX = (touch1.clientX + touch2.clientX) / 2;
			const currentClientY = (touch1.clientY + touch2.clientY) / 2;
			const deltaX = currentClientX - lastClientX;
			const deltaY = currentClientY - lastClientY;
			scale = Math.max(minScale, Math.min(maxScale, startScale * (currentDistance / lastDistance)));
			// 更新元素的 transform 属性以进行缩放和平移
			element.style.transform = `translate(${translateX + deltaX}px,${translateY + deltaY}px) scale(${scale})`;
			if (rebound) {
				// 保持transformOrigin不变
				element.style.transformOrigin = initialTransformOrigin;
			}
		}
		function handleTouchEnd(event) {
			if (isScaling) {
				if (rebound) {
					setToOriginal();
				} else {
					scale < 1 ? setToOriginal() : recordPosition();
				}
			}
		}
		// 计算两个触摸点之间的距离
		function getDistance(touch1, touch2) {
			return Math.sqrt(Math.pow(touch2.clientX - touch1.clientX, 2) + Math.pow(touch2.clientY - touch1.clientY, 2));
		}
		// 还原到初始状态
		function setToOriginal() {
			isScaling = false;
			element.style.transition = transition + 'ms ease';
			element.style.transform = 'translate(0, 0) scale(1)';
			scale = 1;
			translateX = 0;
			translateY = 0;
			hideButton();
		}
		// 记录最后的缩放比例和平移位置
		function recordPosition() {
			isScaling = false;
			lastClientX = 0;
			lastClientY = 0;
			lastDistance = 0;
			startScale = scale;
			// 保存最后的平移位置
			const matrix = new WebKitCSSMatrix(window.getComputedStyle(element).transform);
			translateX = matrix.m41;
			translateY = matrix.m42;
			showButton();
		}
		element.addEventListener('touchstart', handleTouchStart);
		element.addEventListener('touchmove', handleTouchMove);
		element.addEventListener('touchend', handleTouchEnd);
	},
	/**
	 * @Author: lcq
	 * @Date: 2024-04-25 09:18:12
	 * @brief: 取消缩放
	 * @param {*} element - DOM节点
	 * @return {void}
	 */
	cancelPinchZoom(element) {
		let pinchZoomId = element.getAttribute('pinch-zoom');
		if (!pinchZoomId) throw new Error('该节点未添加过缩放功能');
		element.setAttribute('pinch-zoom', '');
		element.removeEventListener('touchstart', handleTouchStart);
		element.removeEventListener('touchmove', handleTouchMove);
		element.removeEventListener('touchend', handleTouchEnd);
		let reduction = document.getElementById('pinchZoomReduction' + pinchZoomId);
		if (!!reduction) element.parentNode.removeChild(reduction);
	},
	/**
	 * @Author: lcq
	 * @Date: 2024-04-25 15:48:02
	 * @brief: 生成唯一ID
	 * @return {*}
	 */
	generateUniqueId() {
		const timestamp = Date.now().toString(36);
		const random = Math.random().toString(36).substr(2, 9);
		return `${timestamp}-${random}`;
	},
};

export default scaleController;
export const {enablePinchZoom, cancelPinchZoom, generateUniqueId} =  scaleController